//
//  ViewController.swift
//  ZHPageView
//
//  Created by Rango on 2020/8/26.
//  Copyright © 2020 Rango. All rights reserved.
//

import UIKit

/// 未封装版本
class ViewController: UIViewController {
    
    var segmentItemWidths: [CGFloat] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpUI()
    }
    
    func setUpUI() {
        view.addSubview(contentView)
        view.addSubview(segmentView)
        
        setUpContentView()
        setUpSegmentView()
    }
    
    func setUpContentView() {
        for item in childVces.enumerated() {
            addChild(item.element)
        }
    }
    
    var lastIndex: Int = 0 {
        didSet {
            print("lastIndex==\(lastIndex)")
        }
    }
    var nextIndex: Int = 0 {
        didSet {
            print("nextIndex==\(nextIndex)")
        }
    }
    @objc func segmentItemTap(_ tap: UITapGestureRecognizer) {
        //guard let label = tap.view as? ZHSegmentItemLabel else { return }
        //guard let index = tap.view?.superview?.subviews.firstIndex(of: label) else { return }
        if let index = tap.view?.tag {
            nextIndex = index
            if abs(nextIndex - lastIndex) > 1 {
                contentView.setContentOffset(CGPoint(x: CGFloat(index) * self.sWidth, y: 0), animated: false)
                scrollOrTapEnd(isScroll: false)
            } else {
                contentView.setContentOffset(CGPoint(x: CGFloat(index) * self.sWidth, y: 0), animated: true)
            }
        }
    }
    let margin: CGFloat = 8 // 标题文本左右边距
    func setUpSegmentView() {
        segmentItemWidths.removeAll()
        for item in children.enumerated() {
            let label = ZHSegmentView.ZHItemLabel()
            label.text = item.element.title
            label.tag = item.offset
            label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(segmentItemTap(_ :))))
            label.isUserInteractionEnabled = true
            segmentView.addSubview(label)
            
            if item.offset == 0 {
                label.zoomTitle(with: 1, animated: false)
            }
            
            //segmentItemWidths.append(100) // 等宽
            // 自动宽度
            label.sizeToFit()
            segmentItemWidths.append(label.frame.width + 2 * margin)
        }
    }
    
    func segmentLayoutSubviews() {
        
        var aX: CGFloat = 0
        let aY: CGFloat = 0
        var aW: CGFloat = 0
        let aH: CGFloat = segmentView.frame.height
        for item in segmentView.subviews.enumerated() {
            aW = segmentItemWidths[item.offset]
            aX += item.offset == 0 ? 0 : segmentItemWidths[item.offset - 1]
            item.element.frame = CGRect(x: aX, y: aY, width: aW, height: aH)
        }
        
        let width: CGFloat = CGFloat(segmentView.subviews.count) * aW
        segmentView.contentSize = CGSize(width: width, height: 0)
    }
    
    let sWidth: CGFloat = UIScreen.main.bounds.width
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        let kWidth: CGFloat = view.frame.width
        let kHeight: CGFloat = view.frame.height
        
        let segmentViewX: CGFloat = 0
        let segmentViewY: CGFloat = 84
        let segmentViewW: CGFloat = kWidth
        let segmentViewH: CGFloat = 44
        segmentView.frame = CGRect(x: segmentViewX, y: segmentViewY, width: segmentViewW, height: segmentViewH)
        segmentLayoutSubviews()
        
        let contentViewX: CGFloat = 0
        let contentViewY: CGFloat = segmentView.frame.maxY
        let contentViewW: CGFloat = kWidth
        let contentViewH: CGFloat = kHeight - contentViewY
        contentView.frame = CGRect(x: contentViewX, y: contentViewY, width: contentViewW, height: contentViewH)
        contentView.contentSize = CGSize(width: CGFloat(children.count) * sWidth, height: 0)
        
        for item in children.enumerated() {
            if item.offset == 0 {
                item.element.view.frame = contentView.bounds
                contentView.addSubview(item.element.view)
            }
        }
    }
    
    private lazy var childVces: [UIViewController] = {
        let vc1 = ZHExampleViewController()
        vc1.title = "国际"
        let vc2 = ZHExampleTableController()
        vc2.title = "国内"
        let vc3 = ZHExampleViewController()
        vc3.title = "游戏频道"
        let vc4 = ZHExampleTableController()
        vc4.title = "体育"
        let vc5 = ZHExampleViewController()
        vc5.title = "情感专栏"
        let vc6 = ZHExampleTableController()
        vc6.title = "科技"
        let vc7 = ZHExampleViewController()
        vc7.title = "娱乐八卦"
        let vc8 = ZHExampleTableController()
        vc8.title = "纪录片"
        return [vc1, vc2, vc3, vc4, vc5, vc6, vc7, vc8]
    }()
    
    /// 分页区
    private lazy var segmentView: UIScrollView = {
        $0.showsVerticalScrollIndicator = false
        $0.showsHorizontalScrollIndicator = false
        
        return $0
    }(UIScrollView())
    
    /// 内容区
    private lazy var contentView: UIScrollView = {
        $0.showsVerticalScrollIndicator = false
        $0.showsHorizontalScrollIndicator = false
        $0.isPagingEnabled = true
        $0.delegate = self
        return $0
    }(UIScrollView())
    
}

extension ViewController {
    // 点击/拖拽结束后
    func scrollOrTapEnd(isScroll: Bool) {
        let index = Int(contentView.contentOffset.x / sWidth)
        lastIndex = index
        let vc = children[index]
        //print("scrollViewDidEndScrollingAnimation---\(index)---\(vc.title!)")
        if !vc.isViewLoaded {
            contentView.addSubview(vc.view)
            
            let aX: CGFloat = CGFloat(index) * sWidth
            let aY: CGFloat = 0
            let aW: CGFloat = contentView.frame.width
            let aH: CGFloat = contentView.frame.height
            vc.view.frame = CGRect(x: aX, y: aY, width: aW, height: aH)
        }
        
        // title 居中
        if let label = segmentView.subviews[index] as? ZHSegmentView.ZHItemLabel {
            var offsetX = label.center.x - sWidth / 2
            if offsetX < 0 { offsetX = 0 } // 左边界
            let maxX = segmentView.contentSize.width - sWidth
            if offsetX > maxX { offsetX = maxX } // 右边界
            segmentView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
            
            // 保证最后状态正常
            for item in segmentView.subviews {
                if let item = item as? ZHSegmentView.ZHItemLabel {
                    if item != label {
                        item.zoomTitle(with: 0, animated: false)
                    } else {
                        item.zoomTitle(with: 1, animated: false)
                    }
                }
            }
        }
    }
}

extension ViewController: UIScrollViewDelegate {
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        // setContentOffset 滑动动画结束时
        //print(#function)
        scrollOrTapEnd(isScroll: true)
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 拖拽动画结束时
        //print(#function)
        scrollViewDidEndScrollingAnimation(scrollView)
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //print("scrollViewDidScroll lastIndex==\(lastIndex)")
        let scale = (scrollView.contentOffset.x / sWidth)
        let leftIndex = Int(scale)
        if scale > 0 && leftIndex < segmentView.subviews.count - 1 { // 边界问题
            let rightScale = scale - CGFloat(leftIndex)
            let rightIndex = leftIndex + 1
            let rightLabel = segmentView.subviews[rightIndex] as? ZHSegmentView.ZHItemLabel
            rightLabel?.zoomTitle(with: rightScale, animated: false)
            print(rightScale)
            let leftLabel = segmentView.subviews[leftIndex] as? ZHSegmentView.ZHItemLabel
            let leftScale = 1 - rightScale
            leftLabel?.zoomTitle(with: leftScale, animated: false)
        }
    }
}

